package com.cstor.liang.web.controller;

import com.cstor.liang.pojo.entity.PlaceEntity;
import com.cstor.liang.pojo.other.PlaceVo;
import com.cstor.liang.pojo.other.ResultJo;
import com.cstor.liang.service.PlaceService;
import com.cstor.liang.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * Created by pomer on 2017/10/17.
 */
@RestController
@RequestMapping("/Place")
public class PlaceController {

    @Autowired
    private PlaceService service;

    @RequestMapping(value = "/getTop", method = RequestMethod.GET)
    public ResultJo getTop(Integer regionId) {
        //数据校验
        if (null == regionId) {
            //校验失败，收集所有错误
            return ResultJo.returnError(1, "缺少regionId");
        }

        //获取指定省市区的“地方”
        return ResultJo.returnOk(
                service.filter(1, regionId,
                        null, null, null, null, null, null));
    }

    @RequestMapping(value = "/getPlace", method = RequestMethod.GET)
    public ResultJo getPlace(Integer placeId) {
        //数据校验
        if (null == placeId) {
            //校验失败，收集所有错误
            return ResultJo.returnError(1, "缺少placeId");
        }

        //获取某个“地方”下的所有“地方”
        return ResultJo.returnOk(
                service.filter(0, placeId,
                        null, null, null, null, null, null));
    }

    @RequestMapping(value = "/select", method = RequestMethod.GET)
    public ResultJo select(@Valid PlaceVo vo, BindingResult error) {
        //数据校验
        if (error.hasErrors()) {
            //校验失败，收集所有错误
            String message = WebUtil.bindingResultCollect(error);
            return ResultJo.returnError(1, message);
        }

        //筛选查询
        return ResultJo.returnOk(
                service.filter(vo.getIsTop(), vo.getParentNodeId(), vo.getType(), vo.getPlaceDesc(),
                        vo.getAdminUserId(), vo.getMaintainUserId(), vo.getPageIndex(), vo.getPageSize()));
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultJo add(PlaceEntity entity) {
        service.addPlace(entity);
        return ResultJo.returnOk("添加成功");
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResultJo update(PlaceEntity entity) {
        service.updatePlace(entity);
        return ResultJo.returnOk("更新成功");
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResultJo delete(Integer placeId) {
        if (null == placeId)
            return ResultJo.returnError(1, "缺少placeId");

        service.deletePlace(placeId);
        return ResultJo.returnOk("删除成功");
    }
}